package pl.edu.uj.ii.battleships.activities;


import java.io.*;

import pl.edu.ii.uj.battleships.server.ClientDescription;
import pl.edu.ii.uj.battleships.server.PackageClient;
import pl.edu.ii.uj.battleships.server.ServerHandler;
import pl.edu.uj.ii.battleships.R;
import pl.edu.uj.ii.battleships.interfaces.Handler;
import pl.edu.uj.ii.battleships.utils.ConfigPropsManager;
import pl.edu.uj.ii.battleships.utils.GameDataManager;
import pl.edu.uj.ii.battleships.utils.Logger;
import pl.edu.uj.ii.battleships.utils.MessageFactory;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends CustomActivity implements Handler {
	
	private TextView debug_textview;
	private ConfigPropsManager propsManager;
	private ServerHandler serverHandler;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Logger.debug("App started.");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        propsManager = new ConfigPropsManager(this);
        Button hostbutton = (Button)findViewById(R.id.button_host);
        hostbutton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), HostActivity.class);
				startActivityForResult(intent, 0);
			}
		});
        
        debug_textview = (TextView)findViewById(R.id.debugtext);
        debug_textview.setText("Connecting to server...");
        
        serverHandler = new ServerHandler(propsManager, this);
        serverHandler.start();
        
        GameDataManager.setServerHandler(serverHandler);

    }

	final android.os.Handler customHandler = new android.os.Handler(){
		public void handleMessage(Message msg){
			String s = (String)msg.obj;
	        if(s.equals(MessageFactory.Prefix.CONNECTION + MessageFactory.getDelimiter() + MessageFactory.Status.OK)) {
	        	debug_textview.setText("Connected to server");
	        	Logger.debug("Connected to server");
	        } else if(s.equals(MessageFactory.Prefix.CONNECTION + MessageFactory.getDelimiter() + MessageFactory.Status.FAILED)){
	        	debug_textview.setText("Failed to connect to server");
	        	Logger.error("Failed to connect to server");
	        } else if(s.equals(MessageFactory.Prefix.CONNECTION + MessageFactory.getDelimiter() + MessageFactory.Status.LOST)){
	        	debug_textview.setText("Connection to server lost.");
	        	Logger.error("Connection to server lost.");
	        }
			
		}
	};

	public android.os.Handler getHandler() {
		return customHandler;
	}

	
}